package lion.web.interceptors.virtual;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import lion.dev.lang.MapJ;
import lion.framework.core.conf.Config;
import lion.framework.core.conf.ConfigManager;
import lion.framework.core.web.request.RequestHandler;
import lion.framework.core.web.request.RequestInterceptor;
import lion.framework.core.web.views.FSResourceView;

/**
 * @author lion
 * @email hl_0074@sina.com
 * @date 2014年6月14日
 */
public class VirtualPathInterceptor implements RequestInterceptor {

	private List<VirtualPath> virtualPaths = new ArrayList<>();

	public VirtualPathInterceptor() {

		Config config = ConfigManager.getConfig("framework");
		List<MapJ> virtualPathMaps = config.getList("framework.web.virtual");
		for (MapJ map : virtualPathMaps) {
			virtualPaths.add(new VirtualPath(map.getString("context"), map.getString("location")));
		}
	}

	/**
	 * 只有文件存在时才处理，文件不存在则交给框架继续处理
	 */
	@Override
	public void intercept(HttpServletRequest request, HttpServletResponse response, RequestHandler handler) throws Exception {

		for (VirtualPath vp : this.virtualPaths) {
			if (vp.matches(handler.getPath())) {
				String realPath = vp.getRealPath(handler.getPath());
				if (realPath != null) {
					new FSResourceView("success", realPath).render(request, response);
					return;
				}
			}
		}

		handler.handle(request, response);
	}
}
